<template>
	<view class="wui-rate">
		<view
			class="rate iconfont"
			:class="[icon, 'rate-position-' + (index + 1), value >= index + 1 ? 'active-rate' : 'default-rate']"
			:style="[sizeComputed, defaultColorComputed, activeColorComputed]"
			v-for="(i, index) in count"
			:key="i"
			@click="change(index + 1)"
			@touchstart="touchstart"
			@touchmove="touchmove"
			@touchend="touchend"
		></view>
	</view>
</template>

<script>
export default {
	name: 'w-rate',
	props: {
		value: {
			type: Number
		},
		count: {
			type: Number,
			default: 5
		},
		icon: {
			type: String,
			default: 'icon-wui-stars'
		},
		size: {
			type: [String, Number],
			default: 46
		},
		defaultColor: {
			type: String,
			default: '#c9c9c9'
		},
		activeColor: {
			type: String,
			default: '#f5220f'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		// 是否支持滑动手势
		touchable: {
			type: Boolean,
			default: true
		}
	},
	computed: {
		sizeComputed() {
			return {
				'--size': uni.upx2px(this.size) + 'px'
			};
		},
		defaultColorComputed() {
			return {
				'--default-color': this.defaultColor
			};
		},
		activeColorComputed() {
			return {
				'--active-color': this.activeColor
			};
		}
	},

	data() {
		return {
			x: 0,
			isTouch: false,
			// 记录位置信息
			starsPositions: []
		};
	},
	watch: {
		x(val) {
			for (let i = 1; i <= this.count; i++) {
				if (val >= this.starsPositions[i].left) {
					this.$emit('input', i);
				}
			}
		}
	},
	mounted() {
		if (this.touchable) {
			for (let i = 1; i <= this.count; i++) {
				uni.createSelectorQuery()
					.in(this)
					.select('.rate-position-' + i)
					.boundingClientRect(data => {
						this.starsPositions[i] = data;
					})
					.exec();
			}
		}
	},
	methods: {
		change(i) {
			if (this.disabled) return;
			if (i === this.value) {
				this.$emit('input', 0);
			} else {
				this.$emit('input', i);
			}
		},
		touchstart() {
			if (this.disabled) return;
			if (this.touchable) {
				this.isTouch = true;
			}
		},
		touchmove(e) {
			if (this.touchable) {
				if (this.isTouch) {
					this.x = e.changedTouches[0].pageX;
				}
			}
		},
		touchend() {
			if (this.touchable) {
				this.isTouch = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.wui-rate {
	display: flex;

	.rate {
		font-size: var(--size);
		width: calc(var(--size) * 1.2);
		height: calc(var(--size) * 1.2);
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 0.2s;
	}

	.default-rate {
		color: var(--default-color);
	}

	.active-rate {
		color: var(--active-color);
	}
}
</style>
